const db = require("../models");
const Farm_baseinfo = db.farm_baseinfo;
const Op = db.Sequelize.Op;

// Create and Save
exports.create = (req, res) => {
      // Validate request
  if (!req.body||req.body.length===0) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }

  // Create a Farm_baseinfo
  const farm_baseinfo = req.body;

  // Save Farm_baseinfo in the database
  Farm_baseinfo.create(farm_baseinfo)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Farm_baseinfo."
      });
    });
  
};

// Create and Save All
exports.createAll = (req, res) => {
  // Validate request
  if (!req.body||req.body.length===0) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }
  
  // Create Admin_groups
  const admin_groups = req.body;

  // Save Admin_groups in the database
  Farm_baseinfo.bulkCreate(admin_groups)
  .then(data => {
    res.send(data);
  })
  .catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while creating the Farm_baseinfo."
    });
  });

};

// Retrieve all from the database.
exports.findAll = (req, res) => {
  const offset = req.query.offset?parseInt(req.query.offset):0;
  const limit = req.query.limit?parseInt(req.query.limit):10;
  const all = req.query.mode==='all'?true:false;
  const hiden = req.query.mode==='hiden'?true:false;
  const mode = all||hiden?false:true;
  const condition = hiden
  ?{
    'deletedAt':{
      [Op.not]:null
    }  
  }
  :{};
  Farm_baseinfo.findAndCountAll({ 
    offset: offset, 
    limit: limit ,
    paranoid:mode,
    where:condition

  })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving farm_baseinfo."
      });
    });
  
};

// Retrieve a single one with attr and value
exports.findByAttr = (req, res) => {
  const offset = req.query.offset?parseInt(req.query.offset):0;
  const limit = req.query.limit?parseInt(req.query.limit):10;
  const all = req.query.mode==='all'?true:false;
  const hiden = req.query.mode==='hiden'?true:false;
  const mode = all||hiden?false:true;

  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  if(!all){
    condition['deletedAt']=hiden
    ?{
        [Op.not]:null 
    }
    :null;
  };
  
  Farm_baseinfo.findAndCountAll({ 
    where: condition , 
    offset:offset,
    limit:limit,
    paranoid:mode
  }).then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving farm_baseinfo."
      });
    });
  
};

// Find a single one with an id
exports.findOne = (req, res) => {
    const id = req.params.id;
    const mode = req.query.mode=='all'?false:true;

    Farm_baseinfo.findByPk(id,{
      paranoid:mode
    })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message: "Error retrieving Farm_baseinfo with id=" + id
        });
      });
  
};

// Update one by the id in the request
exports.update = (req, res) => {
    
    const id = req.params.id;
    Farm_baseinfo.update(req.body, {
    where: { id: id }
  })
    .then(num => {
      if (num == 1) {
        res.send({
          message: "Farm_baseinfo was updated successfully."
        });
      } else {
        res.send({
          message: `Cannot update Farm_baseinfo with id=${id}. Maybe Farm_baseinfo was not found or req.body is empty!`
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Error updating Farm_baseinfo with id=" + id
      });
    });
  
};

// Update one by attr in the request
exports.updateByAttr = (req, res) => {
    
  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  Farm_baseinfo.update(req.body, {
  where: condition
}).then(num => {
    if(num==0){
      res.send({
        message: `Cannot update Farm_baseinfo with ${attr}=${value}. Maybe Farm_baseinfo was not found or req.body is empty!`
      });
    }else{
      res.send({
        message: `${num} items has been updated with ${attr}=${value}.`,
        count: parseInt(num)
      });
    }
  })
  .catch(err => {
    res.status(500).send({
      message: "Error updating Farm_baseinfo." 
    });
  });

};

// update all by ids
exports.updateAll = async (req, res) => {
 
  var messages=[];
  var count = 0;
  for(let index in req.body){
    
    const id = parseInt(req.body[index].id);
    await Farm_baseinfo.update(req.body[index], {
      where: { id: id }
    })
      .then(num => {
        if (num == 1) {
          messages[index]=
          {
            id: id,
            tip: `Farm_baseinfo with id=${id} was updated successfully.`
          };
          count++;
        } else {
          messages[index]=
          {
            id:id,
            warnning: `Cannot update Farm_baseinfo with id=${id}. Maybe Farm_baseinfo was not found or req.body is empty!`
          };
        }
      })
      .catch(err => {
        messages[index]={
          id:id,
          warnning: "Error updating Farm_baseinfo with id=" + id
        };
      });

  };

  res.send({
    success_count:count,
    messages:messages
  });
};
// Delete one with the specified id in the request
exports.delete = (req, res) => {
    const id = req.params.id;
    const mode = req.query.mode=='true'?true:false;
    Farm_baseinfo.destroy({
      where: { id: id },
      force: mode,
      include:{
        model:Farm_unit_info
      }
    }).then(num => {
      if (num == 1) {
        res.send({
          message: `Farm_baseinfo with id=${id} was deleted successfully!`,
          mode:mode
        });
      } else {
        res.send({
          message: `Cannot delete Farm_baseinfo with id=${id}. Maybe Farm_baseinfo was not found!`,
          mode:mode
        });
      }
    })
    .catch(err => {
      res.status(500).send({
        message: "Could not delete Farm_baseinfo with id=" + id,
        mode:mode
      });
    });
};

// Delete all from the database.
exports.deleteAll = (req, res) => {
  const mode = req.query.mode=='true'?true:false;
    Farm_baseinfo.destroy({
        where: {},
        truncate: false,
        force:mode
      })
        .then(nums => {
          res.send({ message: `${nums} items of table Farm_baseinfo were deleted successfully!`,
          mode:mode
         });
        })
        .catch(err => {
          res.status(500).send({
            message:
              err.message || "Some error occurred while removing all farm_baseinfo.",
            mode:mode
          });
        });
};

// Delete all from the database by Attr.
exports.deleteAllByAttr = (req, res) => {
    const mode = req.query.mode=='true'?true:false;
    const attr = req.params.attr;
    const value = req.params.value;
    const condition = {};
    condition[attr]=value;
    Farm_baseinfo.destroy({
        where: condition,
        truncate: false,
        force:mode
      })
        .then(nums => {
          res.send({ 
            message: `${nums} items of table Farm_baseinfo were deleted successfully!`,
            mode:mode
         });
        })
        .catch(err => {
          res.status(500).send({
            message: err.message || "Some error occurred while removing all farm_baseinfo.",
            mode: mode
          });
        });
};

// Restore softdeleted items by id
exports.restore = (req,res)=>{
    const id = req.params.id;

    Farm_baseinfo.restore({
      where:{id:id}
    })
      .then(() => {
        const data=Farm_baseinfo.findByPk(id);
        return data
      })
      .then(data=>{
        res.send({
          result:"Restore Farm_baseinfo with id=" + id +" successfully!",
          data:data
        });
      })
      .catch(err => {
        res.status(500).send({
          message: "Error recovery Farm_baseinfo with id=" + id +".Maybe it doesn't exist or just an unknown error."
        });
      });

};

// Restore softdeleted items All by ids
exports.restoreAll =async (req,res)=>{
  const ids = req.body.ids;

  let count = 0;
  let result = {};
  for(let id of ids){
    await Farm_baseinfo.restore({
      where:{id:id}
    })
      .then(() => {
        const data=Farm_baseinfo.findByPk(id);
        return data
      })
      .then(data=>{
        count++;
        result[id]={
          result:"Restore Farm_baseinfo with id=" + id +" successfully!",
          data:data
        };
      })
      .catch(err => {
        result[id]={
          message: "Error recovery Farm_baseinfo with id=" + id +".Maybe it doesn't exist or just an unknown error."
        };
      });
  };
  res.send({
    success:count,
    error:ids.length-count,
    rows:result
  });
};

// Restore softdeleted items All by attr
exports.restoreAllByAttr = (req,res)=>{
    
  const attr = req.params.attr;
  const value = req.params.value;
  const condition = {};
  condition[attr]=value;
  Farm_baseinfo.restore({
    where:condition
  })
    .then(() => {
      console.log("testing");
      const data=Farm_baseinfo.findAll({where:condition});
      return data
    })
    .then(data=>{
      res.send({
        result:"Restore Farm_baseinfo successfully!",
        count:data.length,
        data:data
      });
    })
    .catch(err => {
      res.status(500).send({
        message: "Error recovery Farm_baseinfo.Maybe it doesn't exist or just an unknown error."
      });
    });  

};
